<!--
 * @页面名称:系统日志
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="table-box">
    <div class="card table-search">
      <el-form :inline="true" :model="formData" class="demo-form-inline">
        <el-form-item label="查询时间:">
          <el-date-picker
            v-model="formData.dataTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="查询内容:">
          <el-input v-model="formData.content"></el-input>
        </el-form-item>
        <el-form-item label="是否高危:">
          <el-checkbox v-model="formData.isHighRisk" class="m-2"></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSubmit">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Download" @click="handleExport">前端导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Download" @click="handleExport2">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card table-main">
      <stable
        :columns="tableSetting.columns"
        :data="tableSetting.data"
        :tablePage="tableSetting.tablePage"
        :toolbarConfigVisible="true"
        :pageSizes="[10, 20, 50, 100, { label: '全部数据', value: -1 }]"
        @pageChange="pageChange"
        @selectionChange="selectionChange"
      ></stable>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted } from "vue";
import dayjs from "dayjs";
import { Download } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/modules/user";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { saveAs } from "file-saver";

const { proxy } = useCurrentInstance();
const userStore = useUserStore();
// 表单绑定字段
const formData = reactive({
  dataTime: [dayjs(new Date()).format("YYYY/MM/DD"), dayjs(new Date()).format("YYYY/MM/DD")] as any,
  content: "",
  isHighRisk: false
});
// 表格配置
const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 50 },
    { title: "用户名", field: "U_Name", width: 100 },
    {
      title: "请求信息",
      type: "expand",
      width: 80,
      slots: {
        content: ({ row }: any) => {
          return row.Log_Content;
        }
      }
    },
    { title: "时间", field: "Log_Time", sortable: true, width: 200 },
    {
      title: "类型",
      field: "Log_Type",
      sortable: true,
      width: 100,
      slots: {
        default: ({ row }: any) => {
          return [<div>{row.Log_Type ? <el-tag>{row.Log_Type}</el-tag> : ""}</div>];
        }
      } as any
    },
    {
      title: "是否高危",
      field: "Log_IsHighRisk",
      sortable: true,
      width: 100,
      slots: {
        default: ({ row }: any) => {
          return [<div>{row.Log_IsHighRisk ? <el-tag type="danger">是</el-tag> : <el-tag type="success">否</el-tag>}</div>];
        }
      }
    },
    { title: "内容", field: "Log_ChangMark", sortable: true },
    { title: "IP", field: "Log_IP", sortable: true, width: 120 }
  ],
  data: [],
  tablePage: {
    showPage: true,
    pageIndex: 1,
    pageSize: 20,
    total: 0
  }
});
// 表格多选数据
const selectionData: any = ref([]);
// 获取操作数据
const getLogData = () => {
  proxy.$vueAxios
    .get("MasterBaseLog/getList", {
      startTime: formData.dataTime[0],
      endTime: formData.dataTime[1],
      keyword: formData.content,
      isHighRisk: formData.isHighRisk,
      uId: userStore.userInfo.U_ID,
      pageIndex: tableSetting.tablePage.pageIndex,
      pageSize: tableSetting.tablePage.pageSize
    })
    .then(async (res: any) => {
      const accountData = await proxy.$vueAxios.get("MasterBaseUsers/Get", {}, { noLoading: true }); // 所有用户数据
      res.List.forEach((item: any) => {
        // 查找第一个数组中U_ID相同的项
        const matchedItem = accountData.List.find((account: any) => account.U_ID === item.U_ID);
        // 如果找到匹配项，处理它
        if (matchedItem) {
          item.U_Name = matchedItem.U_Name;
        }
      });

      tableSetting.data = res.List;
      tableSetting.tablePage.total = res.Count;
    });
};
// 切换分页
const pageChange = ({ pageIndex, pageSize }: { pageIndex: number; pageSize: number }) => {
  tableSetting.tablePage.pageIndex = pageIndex;
  tableSetting.tablePage.pageSize = pageSize;
  getLogData();
};
// 点击搜索
const searchSubmit = () => {
  getLogData();
};
// 多选
const selectionChange = (val: any) => {
  selectionData.value = val;
};
// 前端导出
const handleExport = () => {
  if (selectionData.value.length === 0) {
    proxy.$notify.warning({
      title: "提示",
      message: "未选中任何数据!"
    });
    return false;
  }
  const header = tableSetting.columns.filter(v => v.title).map(v => v.title);
  const filterVal = tableSetting.columns.filter(v => v.title).map(v => v.field);
  const data = selectionData.value.map((v: any) => filterVal.map((j: any) => v[j]));
  import("@/vendor/Export2Excel").then(excel => {
    excel.export_json_to_excel({
      header: header, //表头 必填
      data, //具体数据 必填
      filename: "系统日志表", //非必填
      autoWidth: true, //非必填
      bookType: "xlsx" //非必填
    });
  });
};
// 导出
const handleExport2 = () => {
  if (selectionData.value.length === 0) {
    proxy.$notify.warning({
      title: "提示",
      message: "未选中任何数据!"
    });
    return false;
  }
  signalrEvent();
  const header = tableSetting.columns.filter(v => v.title).map(v => v.title); //表头
  const params = {
    logIdList: selectionData.value.map((v: any) => v.Log_ID),
    str: header,
    clientUser: proxy.signalr.connectionId
  };
  proxy.$vueAxios.download("ExcelTemplate/ExportLog", params, { noLoading: true }).then((res: any) => {
    const fileBlob = new Blob([res], { type: "application/octet-stream;charset=utf-8" });
    saveAs(fileBlob, "系统日志.xlsx");
  });
};
const signalrEvent = () => {
  proxy.signalr.off("SendExportLog");
  proxy.signalr.on("SendExportLog", (res: any) => {
    proxy.$showLoading({ tip: res });
    if (res.trim().startsWith("start")) {
      // 传输开始
      proxy.$showLoading({ tip: res });
    }
    if (res.trim().startsWith("stop")) {
      // 传输结束
      proxy.$hideLoading();
    }
  });
};
onMounted(() => {
  getLogData();
});
</script>

<style scoped lang="scss">
:deep(.vxe-body--expanded-cell) {
  padding: 15px;
  word-wrap: break-word !important;
  white-space: normal !important;
}
.demo-form-inline {
  display: flex;
}
</style>
